package com.example.park2301.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.net.Const
import com.example.park2301.R
import com.example.park2301.databinding.ActivityUserBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlin.math.log

@Route(path = "/app/UserActivity")
@AndroidEntryPoint
class UserActivity : BaseActivity<ActivityUserBinding,UserVIewModel>() {
    override fun initView() {
        //七天不用登录
        val loginTime = SPUtils.getInstance().getLong("loginTime", 0)
        val currentTime = System.currentTimeMillis()
        val day = (currentTime - loginTime) / 1000 / 60 / 60 / 24
        if (day <7){
            start()
        }
        binding.btnLogin.setOnClickListener {
            val uname = binding.loginUname.text.toString()
            val pass = binding.loginPass.text.toString()
            if (uname.isNullOrEmpty()||  pass.isNullOrEmpty()){
                ToastUtils.showLong("输入内容不能为空")
                return@setOnClickListener
            }
//            if (!uname.matches(Regex("^[a-zA-Z0-9]{2,8}$"))){
//                ToastUtils.showLong("用户名格式错误")
//                return@setOnClickListener
//            }
            vm.login(binding.loginUname.text.toString(),binding.loginPass.text.toString())
        }
        binding.loginRegister.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }
    }


    override fun initData() {
        vm.loginData.observe(this){
           Log.i("UserActivity",it.toString())
            SPUtils.getInstance().apply {
                put(Const.TOKEN,it.token)
                put(Const.USERNAME,it.username)
                put(Const.UID,it.id)
                put(Const.ROLE,it.roleid)
                //记录登录时间
                put("loginTime",System.currentTimeMillis())
            }
            start()
        }
    }
    private fun start() {
        if (SPUtils.getInstance().getInt(Const.ROLE,-1)==11){
            ARouter.getInstance().build("/app/MainActivity").navigation()
        }else{
            ARouter.getInstance().build("/app/WebViewActivity").navigation()
        }
        finish()
    }


}